package com.ruoyi.function.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.function.domain.TollBridgeStat;
import com.ruoyi.function.service.ITollBridgeStatService;
import com.ruoyi.common.utils.poi.ExcelUtil;

/**
 * 收费桥梁统计Controller
 * 
 * @author ruoyi
 * @date 2025-09-11
 */
@RestController
@RequestMapping("/function/TollBridgeStat")
public class TollBridgeStatController extends BaseController
{
    @Autowired
    private ITollBridgeStatService tollBridgeStatService;

    /**
     * 查询收费桥梁统计列表
     */
    @PreAuthorize("@ss.hasPermi('function:TollBridgeStat:list')")
    @GetMapping("/list")
    public AjaxResult list(TollBridgeStat tollBridgeStat)
    {
        List<TollBridgeStat> list = tollBridgeStatService.selectTollBridgeStatList(tollBridgeStat);
        
        // 判断是否有搜索条件，如果有则构建树形结构返回
        boolean hasSearchCondition = tollBridgeStat.getRoadName() != null && !tollBridgeStat.getRoadName().isEmpty() ||
                                   tollBridgeStat.getNodeName() != null && !tollBridgeStat.getNodeName().isEmpty();
        
        if (hasSearchCondition) {
            // 有搜索条件时，构建树形结构返回，包含匹配节点及其所有子节点
            List<TollBridgeStat> treeList = buildTree(list);
            return success(treeList);
        } else {
            // 无搜索条件时，返回扁平列表
            return success(list);
        }
    }

    /**
     * 导出收费桥梁统计列表
     */
    @PreAuthorize("@ss.hasPermi('function:TollBridgeStat:export')")
    @Log(title = "收费桥梁统计", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TollBridgeStat tollBridgeStat)
    {
        List<TollBridgeStat> list = tollBridgeStatService.selectTollBridgeStatList(tollBridgeStat);
        // 构建树形结构
        List<TollBridgeStat> treeList = buildTree(list);
        // 只导出第二层的数据，并将第一层的路段名称存入第二层的路段名称中
        List<TollBridgeStat> exportList = new ArrayList<>();
        for (TollBridgeStat parent : treeList) {
            if (parent.getChildren() != null && !parent.getChildren().isEmpty()) {
                @SuppressWarnings("unchecked")
                List<TollBridgeStat> children = (List<TollBridgeStat>) parent.getChildren();
                for (TollBridgeStat child : children) {
                    // 创建新的对象避免修改原数据
                    TollBridgeStat exportItem = new TollBridgeStat();
                    // 复制子节点的所有属性
                    exportItem.setId(child.getId());
                    exportItem.setParentId(child.getParentId());
                    exportItem.setNodeName(child.getNodeName());
                    exportItem.setLeftLength(child.getLeftLength());
                    exportItem.setRightLength(child.getRightLength());
                    exportItem.setAvgLength(child.getAvgLength());
                    exportItem.setRemark(child.getRemark());
                    // 将第一层的路段名称存入第二层的路段名称中
                    exportItem.setRoadName(parent.getRoadName());
                    exportList.add(exportItem);
                }
            }
        }
        ExcelUtil<TollBridgeStat> util = new ExcelUtil<TollBridgeStat>(TollBridgeStat.class);
        util.exportExcel(response, exportList, "收费桥梁统计数据");
    }

    /**
     * 获取收费桥梁统计详细信息
     */
    @PreAuthorize("@ss.hasPermi('function:TollBridgeStat:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tollBridgeStatService.selectTollBridgeStatById(id));
    }

    /**
     * 新增收费桥梁统计
     */
    @PreAuthorize("@ss.hasPermi('function:TollBridgeStat:add')")
    @Log(title = "收费桥梁统计", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TollBridgeStat tollBridgeStat)
    {
        return toAjax(tollBridgeStatService.insertTollBridgeStat(tollBridgeStat));
    }

    /**
     * 修改收费桥梁统计
     */
    @PreAuthorize("@ss.hasPermi('function:TollBridgeStat:edit')")
    @Log(title = "收费桥梁统计", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TollBridgeStat tollBridgeStat)
    {
        return toAjax(tollBridgeStatService.updateTollBridgeStat(tollBridgeStat));
    }

    /**
     * 删除收费桥梁统计
     */
    @PreAuthorize("@ss.hasPermi('function:TollBridgeStat:remove')")
    @Log(title = "收费桥梁统计", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for (Long id : ids) {
            if (tollBridgeStatService.hasChildById(id)) {
                return error("节点存在子节点，请先删除子节点后再删除父节点");
            }
        }
        return toAjax(tollBridgeStatService.deleteTollBridgeStatByIds(ids));
    }

    /**
     * 构建树形结构
     */
    private List<TollBridgeStat> buildTree(List<TollBridgeStat> list) {
        // 构建父子关系映射
        Map<Long, TollBridgeStat> nodeMap = new HashMap<>();
        List<TollBridgeStat> rootNodes = new ArrayList<>();
        
        // 先将所有节点放入map中
        for (TollBridgeStat node : list) {
            nodeMap.put(node.getId(), node);
        }
        
        // 构建父子关系
        for (TollBridgeStat node : list) {
            Long parentId = node.getParentId();
            if (parentId != null && parentId != 0) {
                TollBridgeStat parent = nodeMap.get(parentId);
                if (parent != null) {
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<TollBridgeStat>());
                    }
                    @SuppressWarnings("unchecked")
                    List<TollBridgeStat> children = (List<TollBridgeStat>) parent.getChildren();
                    children.add(node);
                }
            } else {
                rootNodes.add(node);
            }
        }
        
        return rootNodes;
    }
}
